package open.panxiong.shared.http.controller

import android.content.Context
import fi.iki.elonen.NanoHTTPD.IHTTPSession
import fi.iki.elonen.NanoHTTPD.Response
import fi.iki.elonen.NanoHTTPD.getMimeTypeForFile
import fi.iki.elonen.NanoHTTPD.newFixedLengthResponse
import open.panxiong.shared.http.annotation.NanohttpdApi
import open.panxiong.shared.http.config.ConstConfig
import open.panxiong.shared.http.model.ImageItem
import open.panxiong.shared.http.model.NanohttpdResponse
import open.panxiong.shared.util.generateThumbnail
import open.panxiong.shared.util.isImageFile
import java.io.File
import java.io.FileInputStream
import java.net.URLDecoder

class ImageController {

    // 获取图片的缩略图列表
    @NanohttpdApi("/api/get-image-thumbnail-list")
    fun getImageThumbnailList(context: Context, session: IHTTPSession): Response {
        try {
            val items = mutableListOf<ImageItem>()
            val fileList = ConstConfig.getShareFileList(context)
            val thumbnailTempDir = ConstConfig.getTempFileDirectory(context).absolutePath    // 临时目录
            for (file in fileList) {
                if (!file.isFile || !isImageFile(file.name)) {
                    continue
                }
                val thumbnailFile = File(thumbnailTempDir + File.separator + file.name)
                if (!thumbnailFile.exists() || !thumbnailFile.isFile) {
                    // 生成缩略图
                    if (!generateThumbnail(file, thumbnailFile, 150, 60)) continue
                }
                val item = ImageItem()
                item.name = thumbnailFile.name
                item.thuUrl =
                    "${ConstConfig.API_PREFIX_DOWNLOAD}${ConstConfig.TEMP_FILE_DIRECTORY}/${file.name}"
                item.thuSize = thumbnailFile.length()
                item.oriUrl = "${ConstConfig.API_PREFIX_DOWNLOAD}${file.name}"
                item.oriSize = file.length()
                items.add(item)
            }
            return NanohttpdResponse(data = items).toJson()
        } catch (e: Exception) {
            return NanohttpdResponse().to500(e.message.toString())
        }
    }

    // 直接获取缩略图图标
    @NanohttpdApi("/api/get-image-thumbnail")
    fun getImageThumbnail(context: Context, session: IHTTPSession): Response {
        try {
            var filename = session.parameters["filename"]?.last()
            if (filename.isNullOrEmpty()) {
                return NanohttpdResponse(code = -1, msg = "文件名错误").toJson()
            }
            filename = URLDecoder.decode(filename, Charsets.UTF_8.name())

            val file = ConstConfig.getShareFileValue(context, filename)

            if (!file.exists() || !file.isFile || !isImageFile(file.name)) {
                return NanohttpdResponse().to404()
            }
            val thumbnailFile = ConstConfig.getTempFileValue(context, filename)
            if (!thumbnailFile.exists()) {
                if (!generateThumbnail(file, thumbnailFile, 150, 60)) {
                    return NanohttpdResponse().to500("生成缩略图失败")
                }
            }

            val response = newFixedLengthResponse(
                Response.Status.OK,
                getMimeTypeForFile(thumbnailFile.name),
                FileInputStream(thumbnailFile),
                thumbnailFile.length()
            )
            return response
        } catch (e: Exception) {
            return NanohttpdResponse().to500(e.message.toString())
        }
    }

}